<?php

/**
 * 
 * 增加文件记录
 * 先判断上传者的容量有没有超出，如果没有，则直接在数据表中插入文件的信息
 * 然后在上传者的已用容量上进行增加
 * 如果超过了容量，则提示出错
 */


include './init_db.php';

$username = defaultGetData('username', '');
$password = defaultGetData('password', '');
$name = defaultGetData('name', '');
$size = (int)(defaultGetData('size', '')); // 文件大小(B) 用于记录文件信息
$size_2 = (int)((defaultGetData('size', '')) / 1024); // 文件大小(KB) 用于计算空间用量
if ($size_2 == 0) {
    $size_2 = 1;
}
$type = defaultGetData('type', 'unknow');
$objectId = defaultGetData('objectId', '');
$upload_time = time();



if (!$username || !$password || !$name || !$objectId) {
    die(json_encode(array(
        'code' => 999,
        'msg' => '参数缺失'
    )));
}


$result = mysqli_query($conn, "SELECT * FROM `cloudDisk_user` WHERE (`username` = '$username' OR `email` = '$username') AND `password` = '$password' LIMIT 1");
if (!mysqli_num_rows($result)) {
    die(json_encode(array(
        'code' => 1000,
        'msg' => '账号或密码错误'
    )));
}


// 判断文件objectId是否存在
$result2 = mysqli_query($conn, "SELECT * FROM `cloudDisk_file` WHERE `objectId` = '$objectId' LIMIT 1");
if (mysqli_num_rows($result2)) {
    // 存在，更新上传时间
    $r = mysqli_query($conn, "UPDATE `cloudDisk_file` SET `upload_time` = '$upload_time', `name` = '$name' WHERE `objectId` = '$objectId'");
    if (!$r) {
        die(json_encode(array(
            'code' => 995,
            'msg' => '操作失败：' . mysqli_error($conn)
        )));
    }
    die(json_encode(array(
        'code' => 200,
        'msg' => '更新记录成功'
    )));
}


// 判断容量有没有超出
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $used_capacity = (int)$row['used_capacity']; // 当前已用空间
    $total_capacity = (int)$row['total_capacity']; // 总空间
    if ($total_capacity - $used_capacity < $size_2) {
        // 剩余的空间不足以存放该文件
        die(json_encode(array(
            'code' => 993,
            'msg' => '存储空间不足，请联系客服扩充容量'
        )));
    }
    // 开始增加该条数据到数据表
    $result = mysqli_query($conn, "INSERT INTO `cloudDisk_file` (`name`, `upload_time`, `size`, `type`, `objectId`, `creator`)
                                    VALUES ('$name', '$upload_time', '$size', '$type', '$objectId', '$username')");
    echo mysqli_error($conn);
    if (!$result) {
        die(json_encode(array(
            'code' => 995,
            'msg' => '操作失败：' . mysqli_error($conn)
        )));
    }
    $used_capacity += $size_2;
    $r = mysqli_query($conn, "UPDATE `cloudDisk_user` SET `used_capacity` = '$used_capacity' WHERE `username` = '$username' LIMIT 1");
    if (!$r) {
        die(json_encode(array(
            'code' => 995,
            'msg' => '操作失败：' . mysqli_error($conn)
        )));
    }
    break;
}

echo json_encode(array(
    'code' => 200,
    'msg' => '增加记录成功'
));
